

function isValid(value)
{
	return  typeof value != 'undefined' && value != null ;
}
module.exports.isValid=isValid;

function isValidArray(value)
{
	return  Array.isArray(value) && value != null && value.length > 0;
}
module.exports.isValidArray=isValidArray;

function isValidString(value)
{
	return  typeof value == "string" && value != null && value.length > 0;
}
module.exports.isValidString=isValidString;

function checkProhibitedWord(value)
{
	//if(isValidString(value) && value.indexOf('صبللصبً ॣ ॣh ॣ ॣ') >=0 )
	if(isValidString(value) && value.indexOf(' ॣ') >=0 )
	{
		var err = new Error('contains prohibited word : ' + value);
		err.code = '999';
		throw err;
	}
}
module.exports.checkProhibitedWord=checkProhibitedWord;

function debug(msg)
{
	if(global.config.debug)
	{
		console.log(process.pid + ': ' + msg);
	}
}

function error(msg)
{
	if(global.config.debug)
	{
		console.error(process.pid + ': ' + msg);
	}
}


module.exports.debug=debug;
module.exports.error=error;

module.exports.errorLog = function(req , code , msg)
{
/*
	var client_address = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.ip;
	if(client_address.indexOf(':ffff:') >= 0)
		client_address = client_address.substr(client_address.lastIndexOf(':')+1);

	if(isValidString(req.body.sessionId))
		error('ERROR ' + req.originalUrl + ' [' + client_address + '] SESSIONID: ' + req.body.sessionId + ' ,CODE: ' + code + ' ,MSG: ' + msg);
	else
		error('ERROR ' + req.originalUrl + ' [' + client_address + '] CODE: ' + code + ' ,MSG: ' + msg);
		*/

	if(isValidString(req.body.sessionId))
		error('ERROR ' + req.originalUrl + ' SESSIONID: ' + req.body.sessionId + ' ,CODE: ' + code + ' ,MSG: ' + msg);
	else
		error('ERROR ' + req.originalUrl + ' CODE: ' + code + ' ,MSG: ' + msg);


	// get ip
	require('dns').lookup(require('os').hostname(), function (err, address, fam) 
	{
		// 로그디비 
		global.log_db.connection.getConnection(function(err,connection)
		{
			if(err) { throw err; }

			var api_name = req.originalUrl;
			api_name = api_name.replace('/'+global.config.version, '');	// 버전뺀 경로 



			var input_param = [global.config.region_id, address, global.config.version , api_name, req.body.sessionId, 'E' , code , msg];
			var sql = 'call inner_addApiLog(?, ?, ?, ?, ?, ?, ?, ?)';

			var query = connection.query(sql, input_param , function (err, rows) 
			{
				connection.release();
				if(err) { throw err; }
			}); // query

		}); // getConnection
	}); // ip
}

module.exports.callLog = function(req)
{
	// debug 일때만 call log 남긴다.
	if(!global.config.debug)
		return;
/*
	var client_address = req.headers['x-forwarded-for'] || req.connection.remoteAddress || req.ip;
	if(client_address.indexOf(':ffff:') >= 0)
		client_address = client_address.substr(client_address.lastIndexOf(':')+1);

	if(isValidString(req.body.sessionId))
		debug('CALLED ' + req.originalUrl + ' [' + client_address + '] SESSIONID: ' + req.body.sessionId);
	else
		debug('CALLED ' + req.originalUrl + ' [' + client_address + ']');
*/

	if(isValidString(req.body.sessionId))
		debug('CALLED ' + req.originalUrl + ' SESSIONID: ' + req.body.sessionId);
	else
		debug('CALLED ' + req.originalUrl );

	// get ip
	require('dns').lookup(require('os').hostname(), function (err, address, fam) 
	{
		// 로그디비 
		global.log_db.connection.getConnection(function(err,connection)
		{
			if(err) { throw err; }

			var api_name = req.originalUrl;
			api_name = api_name.replace('/'+global.config.version, '');	// 버전뺀 경로 

			var input_param = [global.config.region_id, address, global.config.version, api_name, req.body.sessionId, 'C' , null , null];
			var sql = 'call inner_addApiLog(?, ?, ?, ?, ?, ?, ?, ?)';

			var query = connection.query(sql, input_param , function (err, rows) 
			{
				connection.release();
				if(err) { throw err; }
			}); // query

		}); // getConnection
	}); // ip
}

module.exports.callLog2 = function(req)
{
	// get ip
	require('dns').lookup(require('os').hostname(), function (err, address, fam) 
	{
		// 로그디비 
		global.log_db.connection.getConnection(function(err,connection)
		{
			if(err) { throw err; }

			var api_name = req.originalUrl;
			api_name = api_name.replace('/'+global.config.version, '');	// 버전뺀 경로 

			var input_param = [global.config.region_id, address , global.config.version, api_name, req.body.sessionId, 'C' , null , null];
			var sql = 'call inner_addApiLog(?, ?, ?, ?, ?, ?, ?, ?)';

			var query = connection.query(sql, input_param , function (err, rows) 
			{
				connection.release();
				if(err) { throw err; }
			}); // query

		}); // getConnection
	}); // ip
}

module.exports.sessionTraceLog = function(req)
{
	// 로그디비 
	global.log_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var apiName = req.originalUrl;
		apiName = apiName.replace('/'+global.config.version, '');	// 버전뺀 경로 

		var input_param = [global.config.region_id, global.config.version, req.body.sessionId, apiName];
		var sql = 'call inner_addSessionTraceLog(?, ?, ?, ?)';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }
		}); // query

	}); // getConnection
}



module.exports.incPageViewCount = function(articleId , appId , appVersion)
{

	if(!isValidString(String(articleId)) || !isValidString(appId) || !isValidString(appVersion))
		return;

	// 변경하니까 master 디비 
	global.master_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var input_param = [articleId , appId , appVersion];
		var sql = 'call api_incPageViewCount(?, ?, ?)';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }
		}); // query

	}); // getConnection
}


// master db에 관련된 쿼리들 간단히 실행.
function exeMasterQuery(sql, inputParam)
{
	// 변경하니까 master 디비 
	global.master_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var query = connection.query(sql, inputParam , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }
		}); // query

	}); // getConnection
}
module.exports.exeMasterQuery = exeMasterQuery;






// 푸시보낸 시간 기록 
module.exports.changePushTime = function(userIdList , msgType)
{
	var inputParam = [userIdList , msgType];
	var sql = 'call inner_setPushTime(?, ?)';

	exeMasterQuery(sql , inputParam);
}

module.exports.incPageViewCountWithEncId = function(encId , appId , appVersion)
{

	if(!isValidString(String(encId)) || !isValidString(appId) || !isValidString(appVersion))
		return;

	// 변경하니까 master 디비 
	global.master_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var input_param = [encId , appId , appVersion];
		var sql = 'call api_incPageViewCountWithEncId(?, ?, ?)';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }
		}); // query

	}); // getConnection
}

module.exports.incProfileViewCount = function(sessionId , targetUserKey)
{

	if(!isValidString(sessionId) || !isValidString(targetUserKey))
		return;

	// 변경하니까 master 디비 
	global.master_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var input_param = [sessionId , targetUserKey];
		var sql = 'call api_incProfileViewCount(?, ?)';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }
		}); // query

	}); // getConnection
}


module.exports.getUserIdWithSessionId = function(sessionId , cb)
{

	if(!isValidString(sessionId))
	{
		cb(null,null);
		return;
	}

	// 읽어오니까 replica
	global.replica_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var input_param = [sessionId];
		var sql = 'call inner_getUserIdWithSessionId(?, @userId); SELECT @userId AS userId';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }

			cb(null,rows[1][0].userId);

		}); // query

	}); // getConnection
}



// 0 : ios , 1 : android
module.exports.getOSTypeFromAppId = function(appId)
{
	return appId.toLowerCase().indexOf('ios') >= 0 ? 0 : 1;

}


module.exports.attachZero = function (digit , number)
{
	var str = String(digit);

	var zero = number - str.length;

	for(i = 0 ; i < zero  ; i ++)
	{
		str = '0' + str;
	}

	return str;
};

module.exports.checkParamValue = function(param_name ,  param_value)
{
	if (!isValid(param_value))
	{
		var err = new Error(param_name);
		err.code = '502';	// no param
		throw err;
	}
}

// 총 8자 lower case alphabet + integer
module.exports.passwordGenerate = function()
{
    var text = "";
    var possible = "abcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 8; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}



module.exports.passwordEncrypt = function(str)
{
	var crypto = require('crypto');
	var c = crypto.createHash('sha256').update(str).digest('hex');
	return c;
}


module.exports.makePushConfig = function(follow , comment , like)
{
	var config='';
	for(var i=1;i<=32;i++)
	{
		if(2==i)
			config += follow;
		else if(3==i)
			config += comment;
		else if(4==i)
			config += like;
		else
			config += '1';
	}

	return config;
}


// property value를 '' 로 감싸고 있으므로  ' -> " 로 변경한다.
module.exports.adjustPropValue = function(str) 
{
	return str.split("'").join("\"");
}

//  html 에 별도의 tag가 적용되지 않기 위해 <> 변환
module.exports.adjustHTMLString = function(str) 
{
    return str.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}



module.exports.checkManagerSession = function(sessionKey , cb)
{

	if(!isValidString(sessionKey))
	{
		cb(null,null);
		return;
	}

	global.master_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var input_param = [sessionKey];
		var sql = 'call manage_checkSession(? , @result); SELECT @result as result';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }

			console.log('result : ' + rows[1][0].result);

			cb(null,rows[1][0].result);

		}); // query

	}); // getConnection
}

module.exports.setPushDisableList = function(pushKeyList , cb)
{

	if(!isValidString(pushKeyList))
	{
		if(cb != null) cb();
		return;
	}

	global.master_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var input_param = [pushKeyList];
		var sql = 'call inner_setPushDisable(?)';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }

			if(cb != null) cb();

		}); // query

	}); // getConnection
}


// manager session이 없을 경우 
module.exports.gotoManagerLoginPage = function(req , res) 
{
	req.session.key=null;

	res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
	res.end("<script language=javascript>location.href='/';</script>");
}

// manager session 이 끝났을 경우 
module.exports.notifyManagerSessionExpired = function(req , res) 
{
	req.session.key=null;

	res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
	res.end("<script language=javascript>alert('session expired.'); location.href='/'; </script>");
}


// template 읽어서 그냥 보내준다. 
module.exports.sendTemplate = function(path , res) 
{
	var fs = require('fs');
	fs.readFile(path , function(error,data)
	{
		if(error)
		{
			throw error;
		}

		// 전송.
		res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
		res.end(String(data));
	});
}



module.exports.mkObjectDir = function(baseDir , year , month , day)
{
	var path = baseDir + '/' + year;
	var fs = require('fs');

	// object 넣을때마다 부를거라 존재할 때 에러나는건 무시한다.
	// year
	fs.mkdir(path, 0666, function(err) 
	{
		path += '/' + month;

		// month
		fs.mkdir(path, 0666, function(err) 
		{
			path += '/' + day;
			fs.mkdir(path, 0666, function(err) 
			{
				console.log('mkdir : ' + path);
			});
		});

	});
}

// 반송 메일리스트 invalid로 세팅 , complaint로 지정된거 receive : F 로 세팅
module.exports.setSendMmailInfo = function(invalidList , denyList)
{
	// 바꾸는거니까 master
	global.master_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var input_param = [invalidList,denyList];
		var sql = 'call api_setSendmailInfo(?,?)';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }
		}); // query

	}); // getConnection
}



// page cache 변경 
module.exports.changePageCache = function(pageType , pageContent)
{
	// 바꾸는거니까 master
	global.master_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var input_param = [pageType, pageContent];
		var sql = 'call inner_changePageCache(?,?)';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }
		}); // query

	}); // getConnection
}


module.exports.getPageCache = function(sessionId , pageType, cb)
{
	// 읽어오니까 replica
	global.replica_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var input_param = [sessionId, pageType];
		var sql = 'call api_getPageCache(?, ?, @userId, @appid, @refresh, @content); SELECT @userId AS userId, @appId AS appId, @refresh AS refresh, @content AS content';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }

			if(!rows[1][0].userId)
			{
				var err = new Error('Invalid session ID : ' + sessionId);
				err.code = '522';
				throw err;
			}

			cb(null,rows[1][0]);

		}); // query

	}); // getConnection
}

module.exports.getSimpleTimelineData = function(userId, cb)
{
	var articleCount = 4;	// 4개씩 얻어온다. 5->4
	var thumbnailSizeId=1;  // 모바일용 큰거

	// 읽어오니까 replica
	global.replica_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var input_param = [userId, articleCount , thumbnailSizeId , global.config.storage.download.url];		
		var sql = 'call inner_getSimpleTimeline(?, ?, ?, ?)';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }

			cb(null,rows[0]);

		}); // query

	}); // getConnection
}

module.exports.getPageCacheAndSimpleTimeline = function(sessionId , pageType, cb)
{
	var articleCount = 4;	// 4개씩 얻어온다. 5->4
	var thumbnailSizeId=1;  // 모바일용 큰거

	// 읽어오니까 replica
	global.replica_db.connection.getConnection(function(err,connection)
	{
		if(err) { throw err; }

		var input_param = [sessionId, pageType, articleCount, thumbnailSizeId, global.config.storage.download.url];
		var sql = 'call api_getPageCacheAndSimpleTimeline(?, ?, ?, ?, ?, @appid, @refresh, @content); SELECT @appId AS appId, @refresh AS refresh, @content AS content';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();
			if(err) { throw err; }


			if(!rows[2][0].appId)
			{
				var err = new Error('Invalid session ID : ' + sessionId);
				err.code = '522';
				throw err;
			}

			var ret = rows[2][0];
			ret.timelineData = rows[0];


			cb(null, ret);

		}); // query

	}); // getConnection
}


module.exports.getExplorerData = function(cb)
{
	var eventCount = 5;
	var articleCount = 4;	// 4개씩 얻어온다. 5->4
	var thumbnailSizeId=1;  // 모바일용 큰거

	// 읽기만 하니 replica
	global.replica_db.connection.getConnection(function(err,connection)		// 읽기만 하니 replica
	{
		if(err)	{ throw err; }
		
		var input_param = [eventCount , articleCount , thumbnailSizeId , global.config.storage.download.url];			
		var sql = 'call inner_getExplorerData(?,?,?,?)';

		var query = connection.query(sql, input_param , function (err, rows) 
		{
			connection.release();

			if(err){ throw err; }

			var ret = {'code' : 200 , 'body' : []};

			ret.body[0] = {'itemType' : 'event' 
							, 'data' : rows[0]};

			ret.body[1] = {'itemType' : 'articleList' 
							,'itemName' : 'FEATURED' 
							,'listType' : 'featured' 
							,'data' : rows[1]};

			ret.body[2] = {'itemType' : 'articleList' 
							,'itemName' : 'MY FEEDS' 
							,'listType' : 'timeline' }; // data는 뒤에 세팅한다. 

			ret.body[3] = {'itemType' : 'articleList' 
							,'itemName' : 'Weekly HOT' 
							,'listType' : 'weeklyHot' 
							,'data' : rows[2]};

			ret.body[4] = {'itemType' : 'articleList' 
							,'itemName' : 'Today\'s HOT' 
							,'listType' : 'dailyHot' 
							,'data' : rows[3]};


			ret.body[5] = {'itemType' : 'articleList' 
							,'itemName' : 'RECENT' 
							,'listType' : 'recent' 
							,'data' : rows[4]};



			ret.body[6] = {'itemType' : 'subjectList' 
							,'itemName' : 'POPULAR' 
							,'listType' : 'subject' 
							,'data' : rows[5]};

			// return
			cb(null, ret);
		
		}); 

	}); // getConnection

}

